package com.lunasoft.proxy;

import com.lunasoft.protobuf.TESMsg;
import io.netty.channel.*;

/**
 * @author Jierry
 * @version 2016/7/14.
 */
public class ProxyBackendHandler extends ChannelInboundHandlerAdapter {
    private final Channel inboundChannel;

    public ProxyBackendHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(">>>>>>>>>>ACTIVE>>>>>>>>>>");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(">>>>>>>>>>IN-ACTIVE>>>>>>>>>>");
        ProxyFrontendHandler.closeOnFlush(inboundChannel);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Target server is:" + ctx.channel().remoteAddress()+"\r\n");
        System.out.println("Target server returns data:" + msg+"\r\n");
        System.out.println("ToClient:" + inboundChannel.remoteAddress()+"\r\n");
        TESMsg.BasicMsg resp = (TESMsg.BasicMsg)msg;
        inboundChannel.writeAndFlush(resp).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    inboundChannel.read();
                } else {
                    future.channel().close();
                }
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ProxyFrontendHandler.closeOnFlush(ctx.channel());
    }
}
